from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx.shared import RGBColor, Mm, Pt, Inches, Cm
from docx.enum.section import WD_ORIENTATION
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
import os
from openpyxl import load_workbook
import datetime
import re

result_list = []
picture_list = []
error_pic = []


def add_header(doc, head_text, tail_text, level, font_size=18):
    heading = doc.add_heading("", level=level)
    heading.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    head_run = heading.add_run(head_text)
    head_run.bold = False
    head_run.font.name = u'Times New Roman'
    head_run.font.size = Pt(font_size)
    head_run.font.color.rgb = RGBColor(0, 0, 0)
    # head_run.element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体')
    tail_run = heading.add_run(tail_text)
    tail_run.bold = False
    tail_run.font.name = u'黑体'
    tail_run.font.size = Pt(font_size)
    tail_run.font.color.rgb = RGBColor(0, 0, 0)
    tail_run.element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体')


def add_ver_page(document):
    section = document.add_section()
    new_width, new_height = section.page_height, section.page_width
    section.orientation = WD_ORIENTATION.LANDSCAPE
    section.page_width = new_width
    section.page_height = new_height


def add_hor_page(document):
    section = document.add_section()
    new_width, new_height = section.page_height, section.page_width
    section.orientation = WD_ORIENTATION.PORTRAIT
    section.page_width = new_width
    section.page_height = new_height


def add_paragraph(doc, text, font_name=u'STZhongsong', font_size=18):
    paragraph = doc.add_paragraph()
    paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    run = paragraph.add_run(text)
    run.font.name = font_name
    run.font.size = Pt(font_size)
    run.font.color.rgb = RGBColor(0, 0, 0)
    run.element.rPr.rFonts.set(qn('w:eastAsia'), font_name)


def add_cell(cell, text, width, bold=False):
    p = cell.paragraphs[0]
    run = p.add_run(text)
    run.bold = bold
    p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    cell.width = Inches(width)


def add_cell_roman(cell, text, width, bold=False):
    p = cell.paragraphs[0]
    run = p.add_run(text)
    run.bold = bold
    run.font.name = u'Times New Roman'
    p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    cell.width = Inches(width)


def add_table_header(table):
    hdr_cells = table.rows[0].cells
    add_cell(hdr_cells[0], u'序号', 1, True)
    add_cell(hdr_cells[1], u'知识产权名称', 20, True)
    add_cell(hdr_cells[2], u'类别', 8, True)
    add_cell(hdr_cells[3], u'授权日期', 5, True)
    add_cell(hdr_cells[4], u'授权号', 5, True)
    add_cell(hdr_cells[5], u'获得方式', 5, True)


def load_excel():
    global result_list
    path = os.getcwd()
    filename_list = os.listdir(path)
    excel_name = [excelname for excelname in filename_list if excelname.endswith((".xls", ".xlsx"))][0]
    excel_path = os.path.join(path, excel_name)
    workbook = load_workbook(excel_path)
    sheet = workbook.worksheets[0]
    result_list = []
    for i in range(2, sheet.max_row + 1):
        no = sheet.cell(i, 1).value
        name = sheet.cell(i, 2).value
        ip_type = sheet.cell(i, 3).value
        time = sheet.cell(i, 4).value
        authorize_no = sheet.cell(i, 5).value
        ip_method = sheet.cell(i, 6).value
        if no is None:
            continue
        result_list.append({"no": no, "name": name, "ip_type": ip_type, "time": time, "authorize_no": authorize_no,
                            "ip_method": ip_method})
    return result_list


def deal_time(date):
    if isinstance(date, datetime.date):
        return date.strftime('%Y-%m-%d')
    return date


def add_table(document):
    global result_list
    table = document.add_table(rows=1, cols=6, style='Table Grid')
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.style.font.size = Pt(14)
    table.style.font.color.rgb = RGBColor(0, 0, 0)
    table.style.font.name = u'楷体'
    table.style._element.rPr.rFonts.set(qn('w:eastAsia'), u'楷体')
    add_table_header(table)
    # excel
    # result_list = load_excel()
    for result in result_list:
        row_cells = table.add_row().cells
        add_cell_roman(row_cells[0], result['no'], 1)
        add_cell(row_cells[1], result['name'], 20)
        add_cell(row_cells[2], result['ip_type'], 8)
        add_cell(row_cells[3], deal_time(result['time']), 5)
        add_cell(row_cells[4], result['authorize_no'], 5)
        add_cell(row_cells[5], result['ip_method'], 5)


def load_pictures():
    global picture_list
    path = os.getcwd()
    filename_list = os.listdir(path)
    picture_list = [picturename for picturename in filename_list if
                    picturename.endswith((".jpg", ".png", "PNG", "JPG"))]


def get_pictures(ip_no):
    global picture_list
    pictures = []
    lower_ip_no = ip_no.lower()
    regex = re.compile(r'^' + ip_no + r'[\D]{1}(\s|\S)*')
    regex_lower = re.compile(r'^' + lower_ip_no + r'[\D]{1}(\s|\S)*')
    for pic_name in picture_list:
        match = regex.match(pic_name)
        lower_match = regex_lower.match(pic_name)
        if match or lower_match:
            pictures.append(pic_name)
    return pictures


def generate():
    global result_list
    global error_pic
    document = Document()
    # A4
    section = document.sections[0]
    section.page_height = Mm(297)
    section.page_width = Mm(210)
    add_header(document, '3.', ' 知识产权相关材料', 1)
    add_header(document, '3.1', '符合《工作指引》要求的知识产权汇总表', 2)
    document.add_page_break()
    add_ver_page(document)
    print("----------生成标题------------")
    add_paragraph(document, '***公司')
    add_paragraph(document, '符合《工作指引》要求的知识产权汇总表')
    add_table(document)
    print("----------生成表格------------")
    document.add_page_break()
    add_hor_page(document)
    add_header(document, '3.2', '知识产权证书及相应技术水平证明材料', 2)

    for result in result_list:
        ip_no = 'IP' + result['no']
        name = result['name']
        # if int(no) < 10:
        #     no = '0' + no
        add_header(document, ip_no + ":", name, 3)
        document.add_page_break()
        # 图片处理
        pictures = get_pictures(ip_no)
        path = os.getcwd()
        try:
            for pic in pictures:
                pic_path = os.path.join(path, pic)
                document.add_picture(pic_path, width=Cm(17))
                document.add_page_break()
        except Exception as e:
            error_pic.append(ip_no)
        print("----------生成" + ip_no + "------------")

    sections = document.sections
    for section in sections:
        section.top_margin = Cm(2)
        section.bottom_margin = Cm(2)
        section.left_margin = Cm(2)
        section.right_margin = Cm(2)

    document.save("3. 知识产权相关材料.docx")


if __name__ == "__main__":
    load_excel()
    load_pictures()
    generate()
    print("---------word生成完成------------")
    for ip in error_pic:
        print(ip + "----------图片无法插入，请手动插入-----------------")
    os.system("pause")
